package com.sk.bilibili.view.fragment.live;

import static com.sk.bilibili.utils.StringUtils.str;

import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;

import androidx.constraintlayout.widget.VirtualLayout;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.bumptech.glide.Glide;
import com.sk.bilibili.R;
import com.sk.bilibili.adapter.vlayout.live.InteractiveAdapter;
import com.sk.bilibili.bean.Danmu;
import com.sk.bilibili.bean.Member;
import com.sk.bilibili.callBack.LiveDanmuCallBack;
import com.sk.bilibili.databinding.FragmentLiveInteractiveBinding;
import com.sk.bilibili.event.LiveEvent;
import com.sk.bilibili.model.fragment.live.InteractiveModel;
import com.sk.bilibili.other.LiveDanmuSocketClient;
import com.sk.bilibili.utils.DataUtils;
import com.sk.bilibili.view.fragment.BaseFragment;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

public class InteractiveFragment extends BaseFragment<FragmentLiveInteractiveBinding, InteractiveModel> implements LiveDanmuCallBack {

    private Integer liveId;
    private InteractiveAdapter interactiveAdapter;
    private LiveDanmuSocketClient liveDanmuSocketClient;

    public InteractiveFragment(Integer liveId) {
        this.liveId=liveId;
    }

    @Override
    protected void afterSetView() {
        initData();
        initView();
        bindEvent();
    }

    private void bindEvent() {
        bind.ivSend.setOnClickListener(v -> {
            Danmu danmu=model.createDanmu(str(bind.etSend));
            liveDanmuSocketClient.sendDanmu(danmu);
            bind.etSend.setText("");
        });
    }

    private void initData() {
        String url=model.getUrl(liveId);
        liveDanmuSocketClient=new LiveDanmuSocketClient(url,this);
        model.loadMember();
    }

    private void initView() {
        VirtualLayoutManager manager = new VirtualLayoutManager(getContext());
        bind.rvShow.setLayoutManager(manager);
        DelegateAdapter adapter = new DelegateAdapter(manager);
        interactiveAdapter = new InteractiveAdapter(getContext());
        adapter.addAdapter(interactiveAdapter);
        bind.rvShow.setAdapter(adapter);
    }

    @Override
    public void danmu(Danmu danmu) {
        interactiveAdapter.addData(danmu);
        EventBus.getDefault().post(LiveEvent.danmuEvent(danmu));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        liveDanmuSocketClient.close();
    }

    public void loadMemberSuccess(Member member) {
        bind.avAvatar.setRes(member.getAvatar(),member.getExtra().getPendant());
    }

}